package com.neusoft.neu24.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.neusoft.neu24.Result.CommonResult;
import com.neusoft.neu24.Result.ResultCode;
import com.neusoft.neu24.dto.*;
import com.neusoft.neu24.entity.*;
import com.neusoft.neu24.mapper.FeedbackMapper;
import com.neusoft.neu24.service.IFeedbackService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 监督反馈表 服务实现类
 * </p>
 *
 * @author fyc
 * @since 2024-06-18
 */
@Service
public class FeedbackServiceImpl implements IFeedbackService {

    @Resource
    private FeedbackMapper feedbackMapper;

    @Autowired
    private GridServiceImpl gridService;

    @Override
    public CommonResult<List<Feedback>> listAll() {
        return CommonResult.success(feedbackMapper.listAll());
    }

    @Override
    public CommonResult<List<Feedback2PublicDTO>> listAllByPid(Integer pid) {
        List<Feedback2PublicDTO> feedback2PublicDTOS = feedbackMapper.listAllByPid(pid);
        List<Member> members = feedbackMapper.listAllGridor(pid);
        System.out.println(members);
        for (int i = 0,j = 0; i < feedback2PublicDTOS.size(); i++) {
            Integer gid = feedback2PublicDTOS.get(i).getGid();
            if(j <members.size() && members.get(j).getId().equals(gid)) {
                feedback2PublicDTOS.get(i).setMember(members.get(j));
                j++;
            }else{
                feedback2PublicDTOS.get(i).setMember(null);
            }
            System.out.println(feedback2PublicDTOS.get(i).getMember());
        }
        return CommonResult.success(feedback2PublicDTOS);
    }

    @Override
    public CommonResult<Integer> addFeedbackByPublic(Feedback feedback) {
        Integer gid = findGrid(feedback);
        System.out.println(gid);
        List<Integer> ids = new ArrayList<>();
        if(feedback.getFpid()!= null) ids.add(feedback.getFpid());
        if(feedback.getFcid()!= null) ids.add(feedback.getFcid());
        if(feedback.getFrid()!= null) ids.add(feedback.getFrid());
        List<String> pcr = feedbackMapper.getPCRByIds(ids);
        Integer g = ids.get(ids.size() - 1);

        String address = "";
        for(int i = 0; i < pcr.size(); i++) {
            address += pcr.get(i);
        }
        address+=feedback.getFloc();
        feedback.setFaddress(address);
        feedback.setCreatetime(new Date());


        System.out.println("g: " + g);
        //系统分配网格员
        //查找该网格下正常的网格员
        List<Gridor> gridors = feedbackMapper.getGridorsByGid(g);
        System.out.println("gridors: " + gridors);
        //自动随机分配网格员
        if (gridors.size() > 0) {
            int i = RandomUtil.randomInt(0, gridors.size());
            feedback.setGid(gridors.get(i).getMid());
            feedback.setState(1);
            feedback.setUpdatetime(new Date());
        }

        String msg = "你已经上报成功，感谢你对环保事业的付出 (*^▽^*)";
        return CommonResult.successMsg(feedbackMapper.addFeedbackByPublic(feedback),msg);
    }

    @Override
    public CommonResult<FeedbackInfo> getInfoByFid(Integer fid) {
        FeedbackInfo info = feedbackMapper.getInfoByFid(fid);
        if(info == null) return CommonResult.failed(ResultCode.RESULTSET_IS_EMPTY);
        info.setAqilevel(NumberUtil.max(info.getSo2level(),info.getColevel(),info.getSpmlevel()));
        return CommonResult.success(info);
    }

    @Override
    public CommonResult<List<FeedbackInfo>> getInfos() {
        return CommonResult.success(feedbackMapper.getInfos());
    }

    @Override
    public CommonResult<List<TimeLineDTO>> getTimeLines(Integer id) {
        List<TimeLineDTO> tlDTOS = feedback2TimeLine(feedbackMapper.getTimeLines(id));

        return CommonResult.success(tlDTOS);
    }

    @Override
    public CommonResult<List<Feedback2GridDTO>> getTodoListByGid(Integer gid) {
        if(feedbackMapper.getTodoListByGid(gid).isEmpty()) return CommonResult.failed(ResultCode.RESULTSET_IS_EMPTY);
        return CommonResult.success(feedbackMapper.getTodoListByGid(gid));
    }

    @Override
    public CommonResult<FeedbackInfo> commitFeedback(FeedbackInfo info, Integer fid) {
        FeedbackInfo feedbackInfo = feedbackMapper.getAQI(info);
        Date date = new Date();
        Integer aqi = calculateAQI(feedbackInfo);
        if(aqi == null) return CommonResult.failed(ResultCode.DATA_ERROR);

        feedbackInfo.setAqilevel(aqi);
        feedbackInfo.setUpdatetime(date);
        feedbackMapper.addFeedbackInfo(feedbackInfo);
        Integer fiid = feedbackInfo.getId();

        if(fiid == 0 || fiid == null) return CommonResult.failed(ResultCode.DATA_ERROR);

        System.out.println(fid+"  |  "+ fiid);
        Integer res = feedbackMapper.addFeedback2Info(fid, fiid);
        if(res == 0) return CommonResult.failed(ResultCode.DATA_ERROR);

        Integer update = feedbackMapper.updateFeedbackDoneById(fid, date);
        if (update == 0) return CommonResult.failed(ResultCode.DATA_ERROR);
        String msg = "你已经反馈成功，感谢你对环保事业的付出 (*^▽^*)";
        return CommonResult.successMsg(feedbackInfo, msg);
    }

    @Override
    public CommonResult<List<FeedbackHis2GridDTO>> getHisByGid(Integer gid) {
        List<FeedbackHis2GridDTO> his = feedbackMapper.listFeedbackByGid(gid);
        System.out.println("his: "+his);
        System.out.println("gid: "+gid);

        //关联反馈表和反馈信息表
        List<Integer> ids = his.stream().map(FeedbackHis2GridDTO::getId).collect(Collectors.toList());
        List<FeedbackInfo> infos = feedbackMapper.listInfoByIds(ids);

        for (int i = 0; i < his.size(); i++) {
            his.get(i).setFeedbackInfo(infos.get(i));
        }
        return CommonResult.success(his);
    }

    @Override
    public CommonResult<List<Feedback2AdminDTO>> getList() {
        List<Feedback2AdminDTO> list;
        if ((list = feedbackMapper.getList()).isEmpty()) return CommonResult.failed(ResultCode.DATA_ERROR);
        List<FeedbackInfo> infos = feedbackMapper.getInfos();
        HashMap<Integer,FeedbackInfo> map = new HashMap<>();
        for (FeedbackInfo info : infos) {
            map.put(info.getId(),info);
        }
        for (Feedback2AdminDTO dto : list) {
            dto.setFeedbackInfo(map.get(dto.getFiid()));
        }
        return CommonResult.success(list);
    }

    @Override
    public CommonResult<List<FeedbackInfo2AdminDTO>> getUndo() {
        List<FeedbackInfo2AdminDTO> list;

        if ((list = feedbackMapper.getUndo()).isEmpty()) return CommonResult.failed(ResultCode.DATA_ERROR);
        List<FeedbackInfo> infos = feedbackMapper.getInfos();
        HashMap<Integer,FeedbackInfo> map = new HashMap<>();
        for (FeedbackInfo info : infos) {
            map.put(info.getId(),info);
        }
        for (FeedbackInfo2AdminDTO dto : list) {
            dto.setFeedbackInfo(map.get(dto.getFiid()));
            List<Integer> ids = Arrays.asList(dto.getFpid(), dto.getFcid(), dto.getFrid());
            dto.setGrids(feedbackMapper.getPCRByIds(ids));
        }

        return CommonResult.success(list);
    }

    @Override
    public CommonResult<GridGroupDTO> getPCRs() {
        return CommonResult.success(feedbackMapper.getPCRs());
    }

    @Override
    public CommonResult<FeedbackInfo2AdminDTO> distribute(Feedback feedback) {
        feedback.setUpdatetime(new Date());
        System.out.println(feedback);
        feedbackMapper.updateFeedbackWithGidById(feedback);
        feedbackMapper.insertRelationG2M(feedback.getId(),feedback.getGid());
        FeedbackInfo2AdminDTO mname = feedbackMapper.getMnameById(feedback.getId(),feedback.getGid());
        mname.setId(feedback.getId());
        return CommonResult.success(mname);
    }

    private Integer calculateAQI(FeedbackInfo feedbackInfo) {

        return NumberUtil.max(feedbackInfo.getColevel(),feedbackInfo.getSpmlevel(), feedbackInfo.getSpmlevel());
    }

    public List<TimeLineDTO> feedback2TimeLine(List<Feedback> fbs) {
        ArrayList<TimeLineDTO> tlDTO = new ArrayList<>();
        for (Feedback fb: fbs) {
            ArrayList<TimeLine> tls = new ArrayList<>();
            if (fb.getCreatetime() != null)tls.add(new TimeLine("待处理",fb.getCreatetime()));
            if (fb.getUpdatetime() != null)tls.add(new TimeLine("处理中",fb.getUpdatetime()));
            if (fb.getLastupdatetime() != null)tls.add(new TimeLine("已完成",fb.getLastupdatetime()));
            tlDTO.add(new TimeLineDTO(fb.getId(),tls));
        }
        return tlDTO;
    }


    private Integer findGrid(Feedback feedback) {
        if(feedback.getFrid() == null) {
            if(feedback.getFcid() == null) return feedback.getFpid();
            return feedback.getFcid();
        }
        return feedback.getFrid();
    }





}
